﻿Imports System.Data.SqlClient
Imports System.Xml
Imports System.Drawing

Public Class AgregarPrestamo
    Public MaxNP As Integer = 0
    Private Sub AgregarPrestamo_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: esta línea de código carga datos en la tabla 'EsperanzaDBDataSet.AmortizacionPrestamo' Puede moverla o quitarla según sea necesario.
        Me.AmortizacionPrestamoTableAdapter1.Fill(Me.EsperanzaDBDataSet.AmortizacionPrestamo)
        Me.PrestamosTableAdapter.Fill(Me.EsperanzaDBDataSet.Prestamos)
        Me.SP_ListarTipoPrestamoTableAdapter.Fill(Me.EsperanzaDBDataSet.SP_ListarTipoPrestamo)
        Me.SP_ListarClienteTableAdapter.Fill(Me.EsperanzaDBDataSet.SP_ListarCliente)

        Me.cboTipoPlazo.Items.Add("Mensual")
        Me.cboTipoPlazo.Items.Add("Diario")

        Me.cboTipoPlazo.SelectedIndex = 0
    End Sub

    Private Sub cboRNP_EditValueChanged(sender As Object, e As EventArgs) Handles cboRNP.EditValueChanged
        BuscarCliente(Me.cboRNP.EditValue)
    End Sub

    Private Sub BuscarCliente(ByVal RnpClientesito As String)
        If varConexion.State = ConnectionState.Open Then
            varConexion.Close()
        End If
        Try
            varConexion.Open()
            Const sql As String = "SELECT Nombres + ' ' + Apellidos AS NombreCompleto FROM Clientes WHERE RnpCliente = @RNP"

            Dim cmd As New SqlCommand(sql, varConexion)
            cmd.Parameters.Add("@RNP", SqlDbType.NVarChar, 20).Value = RnpClientesito

            Dim reader As SqlDataReader = cmd.ExecuteReader

            If reader.Read Then
                Me.txtNombre.Text = reader.Item("NombreCompleto")
            End If

            reader.Close()
            varConexion.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub btnCalcular_Click(sender As Object, e As EventArgs) Handles btnCalcular.Click
        RealizarCalculos()
    End Sub

    Private Sub RealizarCalculos()
        Dim TasaInteresMensual As Double = CDbl(Me.txtTasaInteres.Text / 100)
        Dim monto As Double = Me.txtMonto.Text
        Dim Plazo As Double = txtPlazo.Text



        Dim Seguro As Double = monto * 0.035

        Dim Intereses As Double = Math.Round((monto + Seguro + CDbl(Me.txtPapeleo.Text)) * TasaInteresMensual, 2)
        Dim InteresesT As Double = Math.Round(((monto + Seguro + CDbl(Me.txtPapeleo.Text)) * TasaInteresMensual) * Plazo, 2)

        Dim TotalPrestamo As Double = Math.Round(InteresesT + monto + Seguro + CDbl(Me.txtPapeleo.Text), 2)


        Dim AbonoCapital As Double = Math.Round((monto + Seguro + CDbl(Me.txtPapeleo.Text)) / Plazo, 2)

        Dim Mensualidad As Double = Math.Round(AbonoCapital + Intereses, 2)

        txtIntereses.Text = InteresesT
        txtSeguro.Text = Seguro
        txtCuotaMensual.Text = Mensualidad
        txtTotalPrestamo.Text = TotalPrestamo

        Dim ProMesPago As Integer = 1
        Dim Saldo As Double = TotalPrestamo
        Dim Fechin As Date = Date.Now().Date

        Me.dgvAmortizacion.Rows.Clear()

        While (ProMesPago <= Plazo)
            If Saldo < Mensualidad Then
                Mensualidad = Math.Round(Saldo)
            End If

            If Saldo <= (Mensualidad + 10) Then
                Mensualidad = Math.Round(Saldo)
            End If
            Saldo -= Mensualidad
            If cboTipoPlazo.SelectedIndex = 0 Then
                Fechin = Fechin.AddMonths(1)
            Else
                Fechin = Fechin.AddDays(1)
            End If
            If Fechin.DayOfWeek = DayOfWeek.Sunday Then
                Fechin.AddDays(1)
            End If
            Me.dgvAmortizacion.Rows.Add(ProMesPago, Mensualidad, AbonoCapital, Intereses, Saldo, Fechin.ToString)
            ProMesPago += 1
        End While

        Me.btnGuarPrestamo.Enabled = True

    End Sub

    Private Sub btnGuarPrestamo_Click(sender As Object, e As EventArgs) Handles btnGuarPrestamo.Click
        GuardarPrestamo()
    End Sub

    Private Sub GuardarPrestamo()
        If varConexion.State = ConnectionState.Open Then
            varConexion.Close()
        End If
        Try
            Me.PrestamosTableAdapter.InsertarPrestamo(Me.cboRNP.EditValue, Me.cboTipoPrestamo.EditValue, Date.Today, "1", Me.txtMonto.Text, Me.txtIntereses.Text, Me.txtSeguro.Text, Me.txtTotalPrestamo.Text, Me.txtPlazo.Text, Me.txtPapeleo.Text)
            Me.btnAgregarAvales.Enabled = True

            GuardarAmortización()

            Me.btnGuarPrestamo.Enabled = False
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Function ObtenerNumPrestamo() As Integer
        If varConexion.State = ConnectionState.Open Then
            varConexion.Close()
        End If
        Try
            varConexion.Open()
            Const sql As String = "SELECT MAX(NumeroPrestamo) AS MaxNumPrestamo FROM Prestamos"

            Dim cmd As New SqlCommand(sql, varConexion)

            Dim reader As SqlDataReader = cmd.ExecuteReader

            If reader.Read Then
                MaxNP = reader.Item("MaxNumPrestamo")
            End If

            reader.Close()
            varConexion.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        Return MaxNP
    End Function

    Private Sub GuardarAmortización()
        Dim MaxNumeroPrestamo As Integer = ObtenerNumPrestamo()
        Dim Pago As Integer
        Dim CuotaMensual, AbonoCapital, Intereses, Saldo As Double
        Dim Fecha As Date

        'For i = 0 To dgvAmortizacion.RowCount - 1
        '    Pago = dgvAmortizacion(0, i).ToString
        '    CuotaMensual = dgvAmortizacion(1, i).ToString
        '    AbonoCapital = dgvAmortizacion(2, i).ToString
        '    Intereses = dgvAmortizacion(3, i).ToString
        '    Saldo = dgvAmortizacion(4, i).ToString
        '    Fecha = dgvAmortizacion(5, i).ToString

        '    Me.AmortizacionPrestamoTableAdapter.InsertarAmortizacion(MaxNumeroPrestamo, Fecha, AbonoCapital, Intereses, Pago, Saldo)
        'Next

        For Each row As DataGridViewRow In dgvAmortizacion.Rows
            Pago = row.Cells(0).Value
            CuotaMensual = row.Cells(1).Value
            AbonoCapital = row.Cells(2).Value
            Intereses = row.Cells(3).Value
            Saldo = row.Cells(4).Value
            Fecha = row.Cells(5).Value

            If Pago > 0 Then
                Me.InsertarAmortizacionTableAdapter.InsertarAmortizacion(MaxNumeroPrestamo, Fecha, AbonoCapital, Intereses, Pago, Saldo)
            End If
        Next

        Dim rptAmortizacion2 As New rptAmortizacion
        rptAmortizacion2.GenerarReporte(MaxNumeroPrestamo)
        'rptAmortizacion2.ShowRibbonPreviewDialog()
    End Sub

    Private Sub btnAgregarAvales_Click(sender As Object, e As EventArgs) Handles btnAgregarAvales.Click
        AgregaAvales.txtPrestamo.Text = MaxNP
        AgregaAvales.ShowDialog()
    End Sub
End Class